﻿/* Copyright (c) 2015 Slava Naumenko - http://m4w.codeplex.com */

using Microsoft.SharePoint;
using System;
using System.Web.Services;

namespace M4W.ASM.Services
{
    [WebService(Namespace = "M4W.ASM.Services")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]
    [System.ComponentModel.ToolboxItem(false)]
    public class Site : System.Web.Services.WebService
    {
        [WebMethod]
        public string FeatureActivate(string Id)
        {
            string result = "";
            try
            {
                SiteFeatureManage.Invoke(Id, "activate");

                result = "Feature '" + Id + "' activated.";
            }
            catch (Exception ex)
            {
                result = ex.Message.ToString();
            }
            return result;
        }

        [WebMethod]
        public string FeatureDeactivate(string Id)
        {
            string result = "";
            try
            {
                SiteFeatureManage.Invoke(Id, "deactivate");

                result = "Feature '" + Id + "' deactivated.";
            }
            catch (Exception ex)
            {
                result = ex.Message.ToString();
            }
            return result;
        }
    }

    // Invocations

    internal static class SiteFeatureManage
    {
        internal static void Invoke(string Id, string operation)
        {
            Guid fId = new Guid("{" + Id + "}");

            string curl = Helper.GetCurrentUrl();

            using (SPSite site = new SPSite(curl))
            {
                site.RootWeb.AllowUnsafeUpdates = true;

                if (operation == "activate")
                {
                    SPFeature aFeature = null;
                    string FeatureError = "";

                    try
                    {
                        aFeature = site.Features.Add(fId, false, SPFeatureDefinitionScope.Web);
                    }
                    catch (Exception ex)
                    {
                        FeatureError = ex.Message;
                    }

                    try
                    {
                        if (aFeature == null)
                        {
                            site.Features.Add(fId);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (FeatureError == "" || FeatureError.Contains("not installed")) { FeatureError = ex.Message; }

                        throw new Exception(FeatureError);
                    }
                }
                else if (operation == "deactivate")
                {
                    site.Features.Remove(fId);
                }

                site.RootWeb.AllowUnsafeUpdates = false;
            }
        }
    }
}